package com.xyz.study.netty.cases.simple;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * TimeClientHandler
 *
 * @author xyz
 * @version 1.0.0
 * @since 2021/7/2
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private int counter;
    private ByteBuf content;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        content = Unpooled.copiedBuffer(("QUERY TIME ORDER\n").getBytes());
//        ctx.writeAndFlush(content);
        for (int i = 0; i < 100; i++){
            ctx.writeAndFlush("QUERY TIME ORDER\n");
        }
    }
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
//        ByteBuf byteBuf = (ByteBuf) o;
//        byte[] req = new byte[byteBuf.readableBytes()];
//        byteBuf.readBytes(req);
//        String body = new String(req, StandardCharsets.UTF_8);
        String body = (String) o;
        System.out.println("Now is : " + body + "; the counter is : " + ++counter);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
